﻿using ConcreteService;
using Infrastructures;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace SponsorshipWeb.Controllers
{
    public class AgentController : ApiController
    {
        #region service
        UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
        UtilService utilService = ServiceFactory.CreateInstance<UtilService>();
        AgentService service = ServiceFactory.CreateInstance<AgentService>();
        #endregion

        #region 注册
        /// <summary>
        /// 代理官注册-第一步-创建用户信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Agent)]
        [HttpPost]
        public IHttpActionResult Create()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest("请登录");
            string respone = "3";
            string userid = user.UserID.ToString();
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["username"];
            var sex = (Sex)Enum.Parse(typeof(Sex), httpPostedForm["sex"], true);
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            string role = httpPostedForm["Role"];

            var userinfo = service.Get<UserInfo>(userid);

            userinfo.Phone = phone;
            userinfo.NickName = name;
            userinfo.QQ = qq;
            userinfo.Sex = sex;
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Role = APPRole.Student;
            userinfo.Status = CommonStatus.ThirdStep;

            if (!role.IsNullOrEmpty() && role == "Agent")
            {
                userinfo.Role = APPRole.Agent;
                string school = httpPostedForm["school"];
                string resume = httpPostedForm["resume"];
                var httpPostedFile = HttpContext.Current.Request.Files;
                HttpPostedFile logo = httpPostedFile[0];
                string path = FileUtil.SaveFile(logo, FileType.AgentLogo, userid.ToInt(), userid, APPRole.Agent);

                var enumRole = (APPRole)Enum.Parse(typeof(APPRole), role, true);
                userinfo.Role = enumRole;
                AgentService aservice = ServiceFactory.CreateInstance<AgentService>();
                Agent agent = aservice.Get<Agent>(userid);
                Agent newagent = new Agent { AgentNO = userid.ToInt(), Status = CommonStatus.ThirdStep, Name = name, SchoolNO = school.ToInt(), Resume = resume, LogoPath = path, Grade = "", UpdateTime = DateTime.Now };

                if (agent == null)
                {
                    newagent.AgentPassword = GetAgentPassword();
                    newagent.CreateTime = DateTime.Now;
                    aservice.Create<Agent>(newagent, userid);
                }
                else
                {
                    newagent.CreateTime = agent.CreateTime;
                    newagent.AgentPassword = agent.AgentPassword;
                    aservice.Update<Agent>(newagent, userid);
                }
                userinfo.Status = CommonStatus.ThirdStep;
                userinfo.HeadImage = path;
            }
            service.Update(userinfo, userid);
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = respone
            });
        }

        /// <summary>
        /// 代理官注册-第三步-创建主要的信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Agent)]
        [HttpPost]
        public IHttpActionResult CreateMainMes()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userid = user.UserID;

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;

            HttpPostedFile StuIDCardContent = httpPostedFile["StuIDCardContent"];
            HttpPostedFile StuIDCardCover = httpPostedFile["StuIDCardCover"];

            FileUtil.SaveFile(StuIDCardContent, FileType.StuIDCardContent, userid, userid.ToString(), APPRole.Agent);
            FileUtil.SaveFile(StuIDCardCover, FileType.StuIDCardCover, userid, userid.ToString(), APPRole.Agent);

            #region seldomused
            string LDID = httpPostedForm["LDID"];
            string AliPayNo = httpPostedForm["AliPayNo"];
            string BankNo = httpPostedForm["BankNo"];

            var lstse = utilService.ListSeldomUsed(userid, SeldomType.All, APPRole.Agent);
            SeldomUsed se1 = new SeldomUsed(userid, APPRole.Agent, SeldomType.PersonCardNo, LDID);
            SeldomUsed se2 = new SeldomUsed(userid, APPRole.Agent, SeldomType.AliPayNo, AliPayNo);
            SeldomUsed se3 = new SeldomUsed(userid, APPRole.Agent, SeldomType.BankNo, BankNo);

            var existSe1 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.PersonCardNo).FirstOrDefault();
            var existSe2 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.AliPayNo).FirstOrDefault();
            var existSe3 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.BankNo).FirstOrDefault();

            if (existSe1 == null)
            {
                utilService.CreateSeldomUsed(se1, userid.ToString());
            }
            else
            {
                existSe1.Value = LDID;
                utilService.UpdateSeldomUsed(existSe1, userid.ToString());
            }
            if (existSe2 == null)
            {
                utilService.CreateSeldomUsed(se2, userid.ToString());
            }
            else
            {
                existSe2.Value = AliPayNo;
                utilService.UpdateSeldomUsed(existSe2, userid.ToString());
            }
            if (existSe3 == null)
            {
                utilService.CreateSeldomUsed(se3, userid.ToString());
            }
            else
            {
                existSe3.Value = BankNo;
                utilService.UpdateSeldomUsed(existSe3, userid.ToString());
            }
            #endregion

            UserInfo userinfo = userService.Get<UserInfo>(userid.ToString());
            userinfo.Status = CommonStatus.FourStep;
            userService.Update(userinfo, userid.ToString());
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "4"
            });
        }

        #endregion

        #region 代理官信息获取

        /// <summary>
        /// 代理官个人信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Agent)]
        [HttpGet]
        public IHttpActionResult GetAgent()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();

            UserInfo userinfo = userService.Get<UserInfo>(userID);
            Dictionary<string, string> dic = userinfo.ToDictionary();
            var agent = service.Get<Agent>(userID);
            if (agent != null)
            {
                try
                {
                agent.SchoolName = AppConfig.GetSchool(agent.SchoolNO).SchoolName;
                }
                catch
                {

                }

                if (agent == null)
                    return BadRequest("请登录");

                dic.AddOrReplace("Name", agent.Name);
                dic.AddOrReplace("SchoolName", agent.SchoolName);
                dic.AddOrReplace("Resume", agent.Resume);
                dic.AddOrReplace("AgentPassword", agent.AgentPassword);
                dic.AddOrReplace("HeadImage", SystemConfig.Get("UploadHttpPath") + dic["HeadImage"]);
            }

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });

        }
        #endregion

        #region 更新代理官信息

        [HttpPost]
        [CommonAuthorize]
        [UserRole(APPRole.Agent)]
        public IHttpActionResult UpdateAgentInfo()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userid = user.UserID.ToString();
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["username"];
            var sex = (Sex)Enum.Parse(typeof(Sex), httpPostedForm["sex"], true);
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            string role = httpPostedForm["Role"];

            var userinfo = service.Get<UserInfo>(userid);

            userinfo.Phone = phone;
            userinfo.NickName = name;
            userinfo.QQ = qq;
            userinfo.Sex = sex;
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Role = APPRole.Agent;
            userinfo.Status = CommonStatus.FourStep;

            string school = httpPostedForm["school"];
            string resume = httpPostedForm["resume"];
            var httpPostedFile = HttpContext.Current.Request.Files;

            HttpPostedFile StuIDCardContent = httpPostedFile["StuIDCardContent"];
            HttpPostedFile StuIDCardCover = httpPostedFile["StuIDCardCover"];

          
            if (StuIDCardContent.ContentLength != 0)
                FileUtil.SaveFile(StuIDCardContent, FileType.StuIDCardContent, user.UserID, user.UserID.ToString(), APPRole.Agent);
            if (StuIDCardCover.ContentLength != 0)
                FileUtil.SaveFile(StuIDCardCover, FileType.StuIDCardCover, user.UserID, user.UserID.ToString(), APPRole.Agent);
            Agent agent = service.Get<Agent>(userid);
            Agent newagent = new Agent { AgentNO = userid.ToInt(), Status = CommonStatus.ThirdStep, Name = name, SchoolNO = school.ToInt(), Resume = resume, LogoPath = agent.LogoPath, Grade = "", UpdateTime = DateTime.Now };

            newagent.CreateTime = agent.CreateTime;
            newagent.AgentPassword = agent.AgentPassword;
            service.Update<Agent>(newagent, userid);
            service.Update(userinfo, userid);
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "success"
            });
        }

        #endregion

        #region private
        private string GetAgentPassword()
        {
            Random r = new Random();
            string strDateTimeNumber =((char)r.Next(70,112)).ToString();
            Random ran = new Random();
            int strRandomResult = ran.Next(1, 100000);
            return strDateTimeNumber + strRandomResult;
        }
        #endregion
    }
}